package ltd.dujiabao.chat;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author : DuJiabao
 * @Project : io_test
 * @Time : 2021/5/30 21:00
 * @Desc :
 */
public class Client {
  private final String HOST;
  private final Integer PORT;
  private SocketChannel socketChannel;
  private Selector selector;
  private String username;

  public Client(String HOST, Integer PORT, String username) {
    this.HOST = HOST;
    this.PORT = PORT;
    this.username = username;

    try {
      socketChannel = SocketChannel.open(new InetSocketAddress(this.HOST, this.PORT));  // 开启一个socket客户端的通道
      socketChannel.configureBlocking(false);
      selector = Selector.open();
      socketChannel.register(this.selector, SelectionKey.OP_READ); // 注册
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 登录之后，开启接收信息线程和发送消息线程
   */
  public void login() {
    System.out.println(username + " 登录成功");
    receiveMessage();
    sendMessage();
  }

  /**
   * 用于发送消息
   */
  private void sendMessage() {
    new Thread(() -> {
      Scanner scan = new Scanner(System.in);
      while (scan.hasNextLine()) {
        String msg = scan.nextLine();
        msg = username + " : " + msg;
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put(msg.getBytes());
        byteBuffer.flip();
        try {
          socketChannel.write(byteBuffer);
          System.out.println("消息发送成功：" + msg);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }).start();
  }

  /**
   * 用于接收信息
   */
  public void receiveMessage() {
    // 开启读取信息
    new Thread(() -> {
      System.out.println("开始读取消息");
      try {
        while (selector.select() > 0) {
          Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
          while (iterator.hasNext()) {
            System.out.println("有新消息了");
            SelectionKey selectionKey = iterator.next();
            if (selectionKey.isReadable()) {
              SocketChannel channel = (SocketChannel) selectionKey.channel();
              ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
              channel.read(byteBuffer);
              byteBuffer.flip();
              String msg = new String(byteBuffer.array(), 0, byteBuffer.remaining());
              System.out.println(msg);
            }
            iterator.remove();
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }).start();
  }

  public static void main(String[] args) {
    Client client = new Client("127.0.0.1", 8080, "张三");
    client.login();
  }
}
